package com.szw.learn.redismq;

import java.io.IOException;

import javax.websocket.Session;

import com.szw.learn.bean.SendMessageBean;
import com.szw.learn.util.JsonUtil;
import com.szw.learn.websocket.WebsocketEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author 七脉 描述：订阅监听类
 */
public class SubscribeListener implements MessageListener {
	
    private StringRedisTemplate stringRedisTemplate;
	
    private Session session;

    @Autowired
    private WebsocketEndpoint websocketEndpoint;
    
    /**
	 * 订阅接收发布者的消息
	 */
	@Override
	public void onMessage(Message message, byte[] pattern) {
		String msg = new String(message.getBody());
//		System.out.println(new String(pattern) + "主题发布：" + msg);
		SendMessageBean sendMessageBean = JsonUtil.jsonToPojo(msg,SendMessageBean.class);
        if(null!=session){
			for (WebsocketEndpoint we: WebsocketEndpoint.getClients().values()) {
				if(sendMessageBean.getToId().equals(we.getMyname())){
					System.out.println("Send to");
					try {
						we.getSession().getBasicRemote().sendText(msg);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				System.out.println("key: " + we.getKey());
				System.out.println("myname: "+ we.getMyname());
			}
			//session.getBasicRemote().sendText(msg);
		}
	}
	
	public StringRedisTemplate getStringRedisTemplate() {
		return stringRedisTemplate;
	}

	public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
		this.stringRedisTemplate = stringRedisTemplate;
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}
    
}
